<?php
/**
 * Created by PhpStorm.
 * User: geolo
 * Date: 2018/9/21
 * Time: 18:33
 */
namespace app\modules\mch\models;

use app\models\ContentIndex;
use app\models\Content;

use yii\data\Pagination;
class ContentIndexForm extends Model
{
    public $wechat_app_id;
    public $title;
    public $title_s;
    public $is_delete;
    public $type;
    public $id;

    public function rules()
    {

        return [
            [['wechat_app_id'], 'trim'],
            [['wechat_app_id'], 'required'],
            [['id'],'integer'],
        ];
    }

    public function attributeLabels()
    {
        return [
            'wechat_app_id' => '请先申请小程序',

        ];
    }

    public function save($id=null)
    {
        if (!$this->validate())
            return $this->getModelError();
        $model = new ContentIndex();
        $model->attributes = $this->attributes;

        $model->wechat_app_id = $this->wechat_app_id;
        $content = ContentIndex::findOne(['id'=>$id]);
        if(!$content) {

            if ($model->save()) {
                return [
                    'code' => 0,
                    'msg' => '保存成功',
                ];
            }
        }else{
            $title = $this->title;
            $title_s =$this->title_s ;
            $type = $this->type;
            if(ContentIndex::updateAll(['title'=>$title,'title_s'=>$title_s,'type'=>$type],['id'=>$id])){
                return [
                    'code' => 0,
                    'msg' => '修改成功',
                ];
            }

        }
        return $this->getModelError($model);
    }
    public function getdata()
    {
        if (!$this->validate())
            return $this->getModelError();
        $list = ContentIndex::find()->alias('c')
            ->select('c.title,co.title as co_title,co.title_s as co_title_s,co.image,co.content')
            ->leftJoin(['co' => Content::tableName()], 'c.id=co.subject_id')
            ->where(['c.id'=>$this->id,'c.wechat_app_id'=>$this->wechat_app_id])->asArray()->all();
        return [
            'code'=>0,
            'msg'=>'success',
           'data'=>[
               'list'=>$list,
           ]
        ];
    }
}
